package com.schooldate.util;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.schooldate.annotation.JsonIncludeField;
import org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer;

import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by Administrator on 2015-3-18.
 */
public class SimpleJsonFilter extends SimplePropertyPreFilter {

    private String namespace;

    private SimpleJsonFilter(){}

    public SimpleJsonFilter(String namespace){
        this.namespace = namespace;
    }

    @Override
    public boolean apply(JSONSerializer serializer, Object source, String name) {
        Class clazz = source.getClass();
        try {
            Method m = clazz.getDeclaredMethod("getHandler");
            JavassistLazyInitializer initializer = (JavassistLazyInitializer) m.invoke(source, null);
            clazz = initializer.getPersistentClass();
        } catch (Exception e) {

        }

        if (clazz.getAnnotation(Entity.class) != null
                || clazz.getAnnotation(MappedSuperclass.class)!=null){
            try {
                char[] chars = name.toCharArray();
                chars[0] -= 32;
                String m_name = "get" + new String(chars);
                Method method = clazz.getMethod(m_name);
                JsonIncludeField include = method.getAnnotation(JsonIncludeField.class);
                if (include != null){
                    if (Arrays.asList(include.namespace()).contains(namespace)){
                        return true;
                    }
                 }
                return false;
            } catch (Exception e) {
                return false;
            }
        }else return super.apply(serializer, source, name);
    }
}
